<?php

namespace common\modules\wechat\controllers\backend;

use common\modules\wechat\models\backend\Fans;
use common\modules\wechat\models\backend\FansSearch;
use common\modules\wechat\models\backend\FansForm;
use common\components\Controller;
use common\modules\wechat\models\backend\Message;
use common\widgets\pages\GridViewPage;
use common\widgets\grid\BulkAjaxActionBtn;
use Yii;
use yii\filters\VerbFilter;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * FansController implements the CRUD actions for Fans model.
 */
class FansController extends Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors = [];

        $behaviors['verbs'] = [
            'class'   => VerbFilter::className(),
            'actions' => [
                'index'             => ['get'],
                'create'            => ['get', 'post'],
                'update'            => ['get', 'put', 'post'],
                'delete'            => ['post', 'delete'],
                'batch-delete'      => ['post', 'delete'],
                'ajax-batch-delete' => ['post', 'delete'],
            ]
        ];

        return $behaviors;
    }

    /**
     * 批量删除ajax请求
     */
    public function actionAjaxBulkDelete()
    {
        return $this->ajaxBlukAction(function ($ids)
        {
            $models = $this->findModel($ids);
            foreach ($models as $model)
            {
                $model->delete();
            }
            return "删除成功!";
        });
    }

    /**
     * Lists all Fans models.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new FansSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->get());

        $page = $this->createGridViewPage($dataProvider, $searchModel);
        return $page->render();
    }

    /**
     * 用户查看
     * @param $id
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionMessage($id)
    {
        $model = $this->findModel($id);
        $message = new Message($this->getWechat());

        if ($message->load(Yii::$app->request->post())) {
            $message->toUser = $model->open_id;
            if ($message->send()) {
                $this->flash('success', '消息发送成功!');
                $message = new Message($this->getWechat());
            }
        }
        $message->toUser = $model->open_id;

        $searchModel = new MessageHistorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//        $dataProvider->sort = [
//            'defaultOrder' => ['created_at' => SORT_DESC]
//        ];
        $dataProvider->query
            ->wechat($this->getWechat()->id)
            ->wechatFans($model->open_id, $this->getWechat()->original);

        return $this->render('message', [
            'model' => $model,
            'message' => $message,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Creates a new Fans model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new FansForm(['scenario' => FansForm::SCENARIO_CREATE]);

        $model->isNewRecord = true;

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($model->save())
                {
                    Yii::$app->session->setFlash('success', '创建成功!');
                    return $this->redirect(['update', 'id' => $model->id]);
                }
                else
                {
                    Yii::$app->session->setFlash('danger', $model->formatErrors());
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            FansForm::SCENARIO_CREATE,
            [
                'pageTitle' => 'Update',
            ]
        );
        return $page->render();
    }

    /**
     * Updates an existing Fans model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario(FansForm::SCENARIO_UPDATE);

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($model->save())
                {
                    Yii::$app->session->setFlash('success', '更新成功!');
                }
                else
                {
                    Yii::$app->session->setFlash('danger', $model->formatErrors());
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            FansForm::SCENARIO_UPDATE,
            [
                'pageTitle' => 'Update',
            ]
        );
        return $page->render();
    }

    /**
     * Deletes an existing Fans model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Delete multiple Fans model.
     */
    public function actionBatchDelete()
    {
        if (($ids = Yii::$app->request->post('ids')) !== null)
        {
            $models = $this->findModel($ids);
            foreach ($models as $model)
            {
                $model->delete();
            }

            return $this->redirect(['index']);
        }
        else
        {
            throw new HttpException(400);
        }
    }

    /**
     * Finds the Fans model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer $id
     * @return Fans the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = FansForm::findOne($id)) !== null)
        {
            return $model;
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
